<?php

namespace App\Http\Middleware;

use App\Exceptions\AuthException;
use App\Service\AuthService;
use Closure;
use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\Response;

class AuthCheck
{
    protected AuthService $authService;
    public function __construct(AuthService $authService)
    {
        $this->authService = $authService;
    }

    /**
     * Handle an incoming request.
     *
     * @param \Closure(\Illuminate\Http\Request): (\Symfony\Component\HttpFoundation\Response) $next
     * @throws AuthException
     */
    public function handle(Request $request, Closure $next): Response
    {
        //dd($request->route()->action['controller'], $request->path());

        // 判断是否传入Authorization
        if ($request->hasHeader('Authorization')){
            $res = $this->authService->checkAuth($request);
            if (!empty($res)) {
                $request->attributes->add(['user_id' => $res['id']]);
                return $next($request);
            } else {
               // 无权限
                throw new AuthException('无权限，请联系管理员授权');
            }
        } else {
            // 无权限
            throw new AuthException('验证失败，请传入Authorization');
        }
    }
}
